﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using uTrade.Common;
using uTrade.Data.Properties;

namespace uTrade.Data
{
    public class Server
    {
        public string Name { set; get; }
        public string IP { set; get; }
        public int Port { set; get; }
        public string Desc { set; get; }
    }

    public class TdxServer
    {
        private List<Server> lstTdxServers = new List<Server>();

        private Server oAvailServer;

        public TdxServer()
        {
            GetServersFromConfig();
        }

        public Server Available
        {
            get
            {
                return oAvailServer;
            }
        }

        /// <summary>
        /// 同步获取最先ping通的IP
        /// </summary>
        private void GetServersFromConfig()
        {
            if (!File.Exists("./TdxConfig.xml"))
            {
                File.WriteAllText("./TdxConfig.xml", Resource.TdxConfig, Encoding.GetEncoding("GB2312"));
            }
            XmlDocument doc = new XmlDocument();
            doc.Load("./TdxConfig.xml");
            XmlElement Servers = doc.DocumentElement["Servers"];
            XmlNodeList nlist = Servers.ChildNodes;
            List<Task<PingReply>> tasks = new List<Task<PingReply>>();

            var IpList = nlist.Cast<XmlNode>()
                .Select(ser => new Server
                {
                    IP = ser["IP"].InnerText,
                    Name = ser["Name"].InnerText,
                    Port = int.Parse(ser["Port"].InnerText),
                    Desc = ser["Desc"].InnerText
                }).ToList();

            foreach (Server server in IpList)
            {
                Ping ping = new Ping();
                tasks.Add(Task.Run(() => ping.Send(server.IP)));
            }
            Task.WaitAny(tasks.ToArray());
            for (int cnt = 0; cnt < tasks.Count; cnt++)
            {
                if (tasks[cnt].Result.Status == IPStatus.Success)
                {
                    oAvailServer = IpList[cnt];
                    uLog.LogInfo("TDX server:{0}", IpList[cnt].Name);
                    break;
                }
            }
        }
    }
}